package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import io.swagger.util.Json;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private WeChatProperties weChatProperties;

    @Resource
    private UserMapper userMapper;
    public static final String code="https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 用户登入
     * @param userLoginDTO
     * @return
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        //请求微信接口得到openid
        String openid = getOpenid(userLoginDTO.getCode());
        //判断是否为空
        if (openid==null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //查询MySQL数据库，根据openid查询用户是否存在
        User user = userMapper.selectByOpenid(openid);
        //如果用户为空那么是新用户
        if (user==null){
             user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now()).build();
           userMapper.insert(user);
        }

        return user;
    }

    /**
     * 调用微信接口获取openid
     * @param js_code
     * @return
     */
    private String getOpenid(String js_code){
        Map<String, String> hashMap = new HashMap<>();
        hashMap.put("appid",weChatProperties.getAppid());
        hashMap.put("secret",weChatProperties.getSecret());
        hashMap.put("js_code",js_code);
        hashMap.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(code, hashMap);
        JSONObject jsonObject = JSON.parseObject(json);
        return jsonObject.getString("openid");
    }
}
